//
//  AFUtils.swift
//  Runner
//
//  Created by szb on 2023/7/3.
//

import Foundation
import Alamofire

class AFUtils: NSObject {
    
    public static func request(method: HTTPMethod, URLString: String, parameters: [String: Any]?){
        AF.request(URLString, method: method, parameters: parameters).responseJSON{ response in
            switch response.result{
            case let .success(data):
                print(data)
                break
            case let .failure(error):
                print(error)
                break
            }
        }
        
    }
    ///上传文件
    public func upload(URLString: String, data: Data, name: String,  parameters: [String: Any]?){
        
        var parameter = parameters
        
        //2>上传文件
        AF.upload(multipartFormData: { multipartFormData in
            //拼接上传文件的二进制数据
            multipartFormData.append(data, withName: name, fileName: "test", mimeType: "application/octet-stream")
            //遍历参数字典,生成对应的参数数据
            if let parameter = parameter {
                for (k, v) in parameter {
                    let str =  v as! String
                    let strData = str.data(using: .utf8)!
                    // data 是 v 的二进制数据 name 是 K
                    multipartFormData.append(strData, withName: k)
                }
            }
        }, to: URLString)
        .responseJSON { response in
            print(response.result)
            switch response.result{
            case let .success(data):
                //完成回调
                print(data)
                break
            case let .failure(error):
                //在开发网络应用中的时候，错误不要提示给用户，但是错误一定要输出
                print(error)
                break
            }
        }
    }
}
